<template>
  <div class="app-container">
    <!-- 顶部导航 -->
    <div class="top-navbar">
      <!-- <div class="nav-tabs"> -->
      <!-- <el-radio-group v-model="activeTab" size="medium"> -->
      <!-- <el-radio-button label="类别"></el-radio-button>
          <el-radio-button label="客户"></el-radio-button> -->
      <!-- <el-radio-button label="供应商"></el-radio-button> -->
      <!-- <el-radio-button label="商品"></el-radio-button> -->
      <!-- <el-radio-button label="支出"></el-radio-button>
          <el-radio-button label="收入"></el-radio-button> -->
      <!-- </el-radio-group> -->
      <!-- </div> -->

      <div class="search-area">
        <el-select
          v-model="listQuery.parentId"
          size="small"
          clearable
          placeholder="请选择上级类别"
          @change="handleParentChange"
          @clear="handleClear"
        >
          <el-option
            v-for="item in categoryOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>

        <!-- <el-select
          v-model="listQuery.parentId"
          placeholder="选择上级类别"
          style="width: 150px; margin-left: 10px"
        >
          <el-option label="显示启用类别" value="enabled"></el-option>
          <el-option label="显示禁用类别" value="disabled"></el-option>
          <el-option label="显示全部类别" value="all"></el-option>
        </el-select> -->

        <el-button
          type="primary"
          class="search-btn"
          style="margin-left: 10px"
          @click="handleFilter"
          >查询</el-button
        >
      </div>

      <div class="operation-buttons">
        <el-button type="success" icon="el-icon-plus" @click="handleAdd"
          >新增</el-button
        >
        <!-- <el-button @click="handleDisable">禁用</el-button>
        <el-button @click="handleEnable">启用</el-button>
        <el-button @click="handleRefresh">刷新</el-button> -->
      </div>
    </div>

    <!-- 树形表格区域 -->
    <div class="tree-header">
      <span class="section-title">商品分类列表</span>
    </div>
    <el-tree
      ref="tree"
      :data="treeData"
      :props="{
        children: 'children',
        label: 'name',
      }"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
    >
      <span slot-scope="{ node, data }" class="custom-tree-node">
        <span>{{ data.name }}</span>
        <span>
          <el-button type="text" size="mini" @click="handleEdit(data)">
            <i class="el-icon-edit" />
          </el-button>
          <el-button type="text" size="mini" @click="handleDelete(node, data)">
            <i class="el-icon-delete" />
          </el-button>
        </span>
      </span>
    </el-tree>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="temp.id ? '编辑' : '新增'"
      :visible.sync="dialogFormVisible"
      width="50%"
    >
      <el-form
        ref="dataForm"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin: 0 auto"
        :rules="rules"
      >
        <el-form-item label="上级类别">
          <el-select
            v-model="temp.parentId"
            placeholder="请选择上级类别"
            style="width: 100%"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="类别名称" prop="name">
          <el-input v-model="temp.name" placeholder="请输入类别名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selGoodsTypeListApi,
  addGoodsTypeApi,
  updateGoodsTypeByIdApi,
  delGoodsTypeByIdApi,
  selParentGoodsTypeListApi,
} from "@/api/goods";

export default {
  name: "ProductCategory",
  data() {
    return {
      activeTab: "商品",
      treeData: [], // 树形数据
      defaultProps: {
        children: "list",
        label: "name",
      },
      // 搜索条件
      listQuery: {
        name: "",
        page: 1,
        pageSize: 10,
        parentId: null,
      },
      dialogFormVisible: false,
      temp: {
        id: null,
        name: "",
        parentId: null,
      },
      rules: {
        name: [{ required: true, message: "请输入类别名称", trigger: "blur" }],
        parentId: [
          { required: true, message: "请选择上级类别", trigger: "change" },
        ],
      },
      categoryOptions: [
        {
          id: "", // 空字符串表示全部
          name: "全部",
        },
      ],
    };
  },
  watch: {
    // 监听搜索关键字变化
    "listQuery.name"(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getGoodsTypeList();
    this.selParentGoodsTypeList();
  },
  methods: {
    // 过滤节点方法
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 获取商品类别列表
    async getGoodsTypeList() {
      try {
        const res = await selGoodsTypeListApi(this.listQuery);
        console.log(res);
        // 将返回的数据转换为树形结构
        this.treeData = this.formatTreeData(res.records);
      } catch (error) {
        this.$message({
          type: "error",
          message: "获取商品类别列表失败: " + (error.message || "未知错误"),
        });
      }
    },
    // 格式化树形数据
    formatTreeData(data) {
      console.log("收到的数据:", data);

      // 检查是否是包含records的结构
      if (data && data.records) {
        console.log("使用records中的数据");
        // 处理records中的数据，将list重命名为children
        return data.records.map((item) => {
          // 创建新对象，避免修改原始数据
          const newItem = { ...item };

          // 如果有list属性，将其转为children属性
          if (newItem.list && Array.isArray(newItem.list)) {
            newItem.children = newItem.list;
            delete newItem.list; // 删除原list属性
          }

          return newItem;
        });
      }

      // 处理已经是数组的情况（可能是查询返回的扁平结构数据）
      if (Array.isArray(data)) {
        console.log("处理数组数据");

        // 检查第一个元素是否有list属性，说明已有结构
        if (data.length > 0 && data[0].list !== undefined) {
          console.log("将已有list结构转为children");
          return data.map((item) => {
            const newItem = { ...item };
            if (newItem.list && Array.isArray(newItem.list)) {
              newItem.children = newItem.list;
              delete newItem.list;
            }
            return newItem;
          });
        }

        // 下面处理扁平结构数据（查询返回的数据）
        console.log("构建树形结构");

        // 创建一个映射表来存储所有节点
        const nodeMap = {};
        data.forEach((item) => {
          nodeMap[item.id] = { ...item, children: [] };
        });

        // 记录所有parentId，用于找到根节点
        const parentIds = new Set();

        // 构建树形结构
        const result = [];
        data.forEach((item) => {
          const node = nodeMap[item.id];

          // 记录parentId
          if (item.parentId !== null) {
            parentIds.add(item.parentId);
          }

          if (item.parentId === null) {
            // 没有父节点，作为根节点
            result.push(node);
          } else if (nodeMap[item.parentId]) {
            // 有父节点，添加到父节点的children数组
            nodeMap[item.parentId].children.push(node);
          }
        });

        // 如果没有找到任何顶级节点（所有节点都有父节点），则使用一个特殊的假设
        // 例如：假设parentId为1的节点是顶级节点（根据您的数据特征）
        if (result.length === 0 && parentIds.size > 0) {
          console.log(
            "未找到真正的根节点，使用parentId为特定值的节点作为根节点"
          );
          data.forEach((item) => {
            if (item.parentId === 1) {
              result.push(nodeMap[item.id]);
            }
          });
        }

        console.log("转换后的树形数据:", result);
        return result;
      }

      // 如果既不是records结构，也不是数组，则返回空数组
      console.log("未识别的数据结构，返回空数组");
      return [];
    },
    // 查询上级类别
    async selParentGoodsTypeList() {
      try {
        const res = await selParentGoodsTypeListApi();
        this.categoryOptions = [
          {
            id: "",
            name: "全部",
          },
          ...res.data,
        ];
      } catch (error) {
        this.$message({
          type: "error",
          message: "获取上级类别列表失败: " + (error.message || "未知错误"),
        });
      }
    },
    // 查询
    handleFilter() {
      // 确保如果选择了"全部"选项，parentId会被设置为null
      if (this.listQuery.parentId === "") {
        this.listQuery.parentId = null;
      }
      this.getGoodsTypeList();
      this.selParentGoodsTypeList();
    },
    // 重置
    resetTemp() {
      this.temp = {
        id: null,
        name: "",
        parentId: null, // 确保这里使用null而不是空字符串
      };
    },
    // 新增
    handleAdd() {
      this.resetTemp();
      this.dialogFormVisible = true;
    },
    // 编辑分类
    handleEdit(data) {
      this.dialogFormVisible = true;
      this.temp = {
        id: data.id,
        name: data.name,
        parentId: data.parentId || null, // 如果parentId为null或undefined，则设置为null
      };

      // 在$nextTick中等待DOM更新后设置表单的验证状态
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate();
      });
    },
    // 删除节点
    handleDelete(node, data) {
      this.$confirm("此操作将永久删除该商品类别, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await delGoodsTypeByIdApi(data.id);
            if (res.code === 1) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getGoodsTypeList(); // 刷新列表
              this.selParentGoodsTypeList(); // 刷新上级类别列表
            } else {
              this.$message({
                type: "error",
                message: res.msg || "删除失败",
              });
            }
          } catch (error) {
            console.error("删除失败:", error);
            this.$message({
              type: "error",
              message: "删除失败: " + (error.message || "未知错误"),
            });
          }
        })
        .catch(() => {});
    },
    // 提交表单
    submitForm() {
      this.$refs.dataForm.validate(async (valid) => {
        if (valid) {
          try {
            const params = {
              name: this.temp.name,
              parentId: this.temp.parentId,
            };

            let res;
            if (!this.temp.id) {
              // 新增商品类别
              res = await addGoodsTypeApi(params);
            } else {
              // 编辑商品类别
              res = await updateGoodsTypeByIdApi({
                ...params,
                id: this.temp.id,
              });
            }

            if (res.code === 1) {
              this.$message({
                type: "success",
                message: `${this.temp.id ? "编辑" : "新增"}成功!`,
              });
              this.dialogFormVisible = false;
              this.getGoodsTypeList(); // 刷新列表
              this.selParentGoodsTypeList(); // 刷新上级类别列表
            } else {
              this.$message({
                type: "error",
                message: res.msg || `${this.temp.id ? "编辑" : "新增"}失败`,
              });
            }
          } catch (error) {
            console.error("操作失败:", error);
            this.$message({
              type: "error",
              message: "操作失败: " + (error.message || "未知错误"),
            });
          }
        }
      });
    },
    handleDisable() {
      this.$message({
        message: "禁用功能待实现",
        type: "info",
      });
    },
    handleEnable() {
      this.$message({
        message: "启用功能待实现",
        type: "info",
      });
    },
    handleRefresh() {
      this.getGoodsTypeList();
    },
    handleClear() {
      this.listQuery.parentId = null;
    },
    handleParentChange(val) {
      console.log("选择了上级类别：", val);
      if (val === "") {
        // 如果选择了"全部"选项
        this.listQuery.parentId = null;
        console.log("选择了全部，parentId设置为null");
      }

      // 不要在这里直接调用查询，让用户点击查询按钮
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.top-navbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.nav-tabs {
  display: flex;
  margin-right: 20px;

  .el-radio-button__inner {
    padding: 8px 20px;
  }
}

.search-area {
  display: flex;
  align-items: center;
  flex-grow: 1;
  margin-right: 20px;

  .el-input {
    margin-right: 10px;
  }

  .search-btn {
    margin: 0;
    padding: 9px 20px;
  }
}

.operation-buttons {
  white-space: nowrap;

  .el-button {
    margin-left: 8px;

    &:first-child {
      margin-left: 0;
    }
  }
}

// 树形组件样式优化
.el-tree {
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px 0;

  .el-tree-node__content {
    height: 40px;

    &:hover {
      background-color: #f5f7fa;
    }
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  width: 100%;

  > span:first-child {
    color: #606266;
  }

  .el-button {
    padding: 4px 8px;
    margin-left: 8px;

    &:hover {
      color: #409eff;
    }

    &.el-button--text {
      &:hover {
        background-color: transparent;
      }
    }

    i {
      font-size: 16px;
    }
  }
}

// 弹窗样式优化
.el-dialog {
  .el-form {
    padding: 20px 0;
  }

  .dialog-footer {
    padding: 10px 20px 20px;
    text-align: right;

    .el-button {
      padding: 9px 20px;
    }
  }
}

// 响应式优化
@media screen and (max-width: 768px) {
  .top-navbar {
    flex-direction: column;
    align-items: stretch;

    > div {
      margin: 10px 0;
    }
  }

  .search-area {
    flex-wrap: wrap;

    .el-input {
      margin-bottom: 10px;
      width: 100% !important;
    }
  }

  .operation-buttons {
    display: flex;
    justify-content: space-between;

    .el-button {
      flex: 1;
      margin: 0 4px;
    }
  }
}
</style>
